<template>
  <div class="contribution-calendar">
    <!-- 顶部月份已去除 -->
    <div class="calendar-grid-with-labels">
      <div class="calendar-row-labels">
        <span v-for="d in 7" :key="'label-' + d" class="row-label">
          <template v-if="d === 1">周一</template>
          <template v-else-if="d === 7">周日</template>
          <template v-else>&nbsp;</template>
        </span>
      </div>
      <div class="calendar-grid">
        <div
          v-for="(week, wIdx) in weeks"
          :key="wIdx"
          class="week-column"
        >
          <div
            v-for="(day, dIdx) in week"
            :key="dIdx"
            class="day-cell"
            :title="''"
            :style="{ background: day ? getColor(day) : '#f5f5f5' }"
          >
            <template v-if="day">
              <a-tooltip placement="top" :title="getTooltip(day)">
                <div class="cell-inner"></div>
              </a-tooltip>
            </template>
            <template v-else>
              <div class="cell-inner"></div>
            </template>
          </div>
        </div>
      </div>
    </div>
    <div class="calendar-legend">
      <span>少</span>
      <span class="legend-box" :style="{background: colorLevels[1]}" />
      <span class="legend-box" :style="{background: colorLevels[2]}" />
      <span class="legend-box" :style="{background: colorLevels[3]}" />
      <span>多</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { Tooltip as ATooltip } from 'ant-design-vue'

interface DayActivity {
  date: string // yyyy-MM-dd
  loggedIn: boolean
  watchedVideo: boolean
  wroteNote: boolean
  tasks?: string[] // 新增：该日完成的任务
}

const props = defineProps<{
  data: DayActivity[]
  startDate?: string
  endDate?: string
}>()

// 颜色等级
const colorLevels = [
  '#f5f5f5', // 无活跃
  '#d6f5d6', // 浅绿
  '#7fd97f', // 中绿
  '#2e8b57'  // 深绿
]

// 生成日期范围
function getDateRange(start: Date, end: Date) {
  const arr = []
  let dt = new Date(start)
  while (dt <= end) {
    arr.push(dt.toISOString().slice(0, 10))
    dt.setDate(dt.getDate() + 1)
  }
  return arr
}

// 用props.data的最早和最晚日期作为区间
const sortedDates = computed(() => props.data.map(d => d.date).sort())
const minDate = computed(() => sortedDates.value[0])
const maxDate = computed(() => sortedDates.value[sortedDates.value.length - 1])
const dateRange = computed(() => {
  if (!minDate.value || !maxDate.value) return []
  return getDateRange(new Date(minDate.value), new Date(maxDate.value))
})
const days = computed(() => dateRange.value.length)
const weekCount = computed(() => Math.ceil(days.value / 7))

// 活跃数据映射
const activityMap = computed(() => {
  const map: Record<string, DayActivity> = {}
  props.data.forEach(item => {
    map[item.date] = item
  })
  return map
})

// 组织成周列
const weeks = computed(() => {
  const arr: (DayActivity | null)[][] = []
  for (let w = 0; w < weekCount.value; w++) {
    const week: (DayActivity | null)[] = []
    for (let d = 0; d < 7; d++) {
      const idx = w * 7 + d
      const date = dateRange.value[idx]
      week.push(date ? activityMap.value[date] || null : null)
    }
    arr.push(week)
  }
  return arr
})

// 预处理：找到每个月首次出现的weekIdx
const monthToWeekIdx = computed(() => {
  const map: Record<string, number> = {}
  for (let w = 0; w < weeks.value.length; w++) {
    for (let d = 0; d < 7; d++) {
      const idx = w * 7 + d
      const dateStr = dateRange.value[idx]
      if (!dateStr) continue
      const date = new Date(dateStr)
      const ym = `${date.getFullYear()}-${date.getMonth() + 1}`
      if (!(ym in map)) {
        map[ym] = w
      }
    }
  }
  return map
})

function getColor(day: DayActivity) {
  if (!day || !day.loggedIn) return colorLevels[0]
  const count = Number(day.watchedVideo) + Number(day.wroteNote)
  if (count === 0) return colorLevels[1]
  if (count === 1) return colorLevels[2]
  if (count === 2) return colorLevels[3]
  return colorLevels[0]
}

function getTooltip(day: DayActivity) {
  if (!day) return '未完成任务'
  if (day.tasks && day.tasks.length > 0) {
    return day.date + '\n' + day.tasks.map(t => '• ' + t).join('\n')
  }
  if (day.loggedIn) return day.date + '\n已获得积分'
  return day.date + '\n未完成任务'
}

// 获取每一列（每周第一天）的月份标记
function getMonthLabel(weekIdx: number) {
  // 只在每月首次出现的那一列显示
  for (const ym in monthToWeekIdx.value) {
    if (monthToWeekIdx.value[ym] === weekIdx) {
      return ym.split('-')[1] + '月'
    }
  }
  return ''
}
</script>

<style scoped>
.contribution-calendar {
  margin-top: 24px;
  padding: 16px 0 0 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  background: none;
  border-radius: 0;
  box-shadow: none;
  justify-content: flex-end;
  min-width: 320px;
  min-height: 320px;
}
.calendar-grid {
  display: flex;
  flex-direction: row;
  justify-content: center;
}
.week-column {
  display: flex;
  flex-direction: column;
  gap: 10px;
  align-items: center;
}
.day-cell {
  width: 28px;
  height: 28px;
  margin: 4px;
  border-radius: 10px;
  border: 1px solid #e0e0e0;
  box-shadow: none;
  transition: background 0.2s, box-shadow 0.2s, border 0.2s;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  position: relative;
}
.day-cell:hover {
  box-shadow: none;
  border-color: #1890ff;
  z-index: 2;
}
.cell-inner {
  width: 18px;
  height: 18px;
  border-radius: 6px;
}
.calendar-legend {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 0;
  margin-bottom: 8px;
  font-size: 15px;
  font-weight: 500;
}
.legend-box {
  width: 24px;
  height: 18px;
  display: inline-block;
  border-radius: 4px;
  border: 1px solid #eee;
}
.calendar-header-row {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-bottom: 6px;
  margin-left: 36px;
  justify-content: center;
}
.calendar-header-cell {
  width: 28px;
  height: 28px;
  display: flex;
  align-items: flex-end;
  justify-content: center;
  font-size: 16px;
  color: #1890ff;
  font-weight: 600;
}
.label-cell {
  width: 36px;
  background: transparent;
}
.calendar-grid-with-labels {
  display: flex;
  flex-direction: row;
  justify-content: center;
  margin-bottom: 0;
  flex: 1;
  align-items: flex-end;
}
.calendar-row-labels {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  margin-right: 4px;
  width: 36px;
  height: 220px;
}
.row-label {
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  font-size: 15px;
  color: #888;
  font-weight: 500;
  line-height: 28px;
}
</style> 